from flask import Flask, request, jsonify
from flask_cors import CORS
import os
from SVM_predict import AudioRecognizer

app = Flask(__name__)
CORS(app)
recognizer = AudioRecognizer(model_path="D:/graduation design/model_deployment/voc_svm/voc_svm/model.pickle")
# recognizer = AudioRecognizer(model_path="model.pickle")
ALLOWED_EXTENSIONS = set(['aac', 'wav', 'mp3'])
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['POST'])
def upload_audio():

    if 'file' not in request.files:
        return jsonify(status='error', message='No file part'), 400
    file = request.files['file']

    if file.filename == '':
        return jsonify(status='error', message='No selected file'), 400
    if file and allowed_file(file.filename):
        # filename = secure_filename(file.filename)
        filename = 'rev.wav'
        save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(save_path)
        
    #返回识别结果
        predicted_label = recognizer.predict(save_path)
        # 录制视频专用
        # predicted_label = "abnormal_treble(不正常高音)"
        # predicted_label = "normal_bass(正常的低音)"
        # predicted_label = "normal_bass_inside_the_carriage(正常的车厢内低音)"
        # predicted_label = "normal_treble(正常的高音)"
        # predicted_label = "normal_treble_inside_the_carriage(正常的车厢内高音)"
        # predicted_label = "resonant_bass_inside_the_carriage(共振的车厢内低音)"
        # predicted_label = "resonant_treble_inside_the_carriage(共振的车厢内高音)"


        return jsonify(status='success', result=predicted_label, path=save_path), 200
    else:
        return jsonify(status='error', message='File type not allowed'), 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

